package com.easy.framework.common.validate;

import com.easy.framework.common.utils.Func;

import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validation;
import jakarta.validation.ValidationException;
import jakarta.validation.Validator;
import java.util.Set;

/**
 * ValidatorUtils 校验工具类
 */
public class ValidatorUtils {
    private static Validator validator;

    static {
        validator = Validation.buildDefaultValidatorFactory().getValidator();
    }
    /**
     * 验证实体数据
     * @param t 要验证的实体
     * @param groups 验证组（可选）
     * @param <T> 实体类型
     * @throws ValidationException 如果验证失败
     */
    public static <T> void validateEntity(T t, Class<?>... groups){
        if (Func.isEmpty(t)) {
            throw new ValidationException("Entity cannot be null");
        }
        Set<ConstraintViolation<T>> violations = validator.validate(t, groups);
        if (!violations.isEmpty()) {
            String errorMessage = violations.stream()
                    .map(v -> v.getPropertyPath() + ": " + v.getMessage())
                    .findFirst().get()
                    //.collect(Collectors.joining("; "))
                    ;
            throw new ValidationException(errorMessage);
        }
    }
}
